﻿using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.DynamicData;
using System.Web.Routing;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.Expressions;
using NotAClue.Web;
using NotAClue.Web.DynamicData;
using NotAClue.ComponentModel.DataAnnotations;
using System.Linq;

namespace DD_Extensions
{
    public partial class List : System.Web.UI.Page
    {
        protected MetaTable table;

        protected void Page_Init(object sender, EventArgs e)
        {
            //?Canceled=True
            var canceled = Request.QueryString["Canceled"] != null;

            table = DynamicDataRouteHandler.GetRequestMetaTable(Context);
            //GridView1.SetMetaTable(table, table.GetColumnValuesFromRoute(Context));
            if (canceled)
            {
                var defaultValues = Page.GetFilterValuesFromSession(table, table.GetColumnValuesFromRoute(Context));
                GridView1.SetMetaTable(table, defaultValues);
            }
            else
                GridView1.SetMetaTable(table, table.GetColumnValuesFromRoute(Context));

            GridDataSource.EntityTypeFilter = table.EntityType.Name;

            // set initial sort order
            GridQueryExtender.SetInitialSortOrder(table);

            // setup the multicolumn text search
            if (GridQueryExtender.SetupMultiColumnTextSearch(table, GridDataSource, Context, txbMultiColumnSearch))
            {
                MultiSearch.Visible = true;

                // get filter value
                var searchText = Page.GetFilterValueFromSession(table, table.Name + Global.MULTI_COLUMN_SEARCH);
                if (canceled && searchText != null)
                    txbMultiColumnSearch.Text = searchText.ToString();
            }

            GridView1.PageSize = table.GetAttributeOrDefault<TableOptionsAttribute>().PageSize;

            // set pager from session
            var pagerPage = Page.GetFilterValueFromSession(table, table.Name + Global.CURRENT_PAGER_PAGE);
            if (canceled && pagerPage != null)
                GridView1.PageIndex = (int)pagerPage;

            // make search text box be remembered 
            // for browser back button
            Page.DisablePartialRenderingForUpload(table);

            // setup export
            var export = table.GetAttribute<ExportAttribute>();
            if (export != null && export.Export == true)
            {
                ExportSpan.Visible = true;
                if (export.AllowShowAllColumns)
                    ShowAllColumnsCheckbox.Visible = true;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            Title = table.DisplayName;
            GridDataSource.Include = table.ForeignKeyColumnsNames;

            // apply custom auto field generator
            GridView1.ColumnsGenerator = new AdvancedAutoFieldGenerator(table, commandCellPosition: CommandCellPosition.Right);

            // Disable various options if the table is readonly
            if (table.IsReadOnly)
            {
                GridView1.Columns[0].Visible = false;
                //InsertHyperLink.Visible = false;
                GridView1.EnablePersistedSelection = false;
            }

            if (FilterRepeater.Controls.Count == 0 && !MultiSearch.Visible)
                Filters.Visible = false;

            if (FilterRepeater.Controls.Count == 0)
                ClearFiltersDiv.Visible = false;
        }

        protected void Label_PreRender(object sender, EventArgs e)
        {
            Label label = (Label)sender;
            DynamicFilter dynamicFilter = (DynamicFilter)label.FindControl("DynamicFilter");
            QueryableFilterUserControl filter = dynamicFilter.FilterTemplate as QueryableFilterUserControl;
            if (filter != null && filter.FilterControl != null)
                label.AssociatedControlID = filter.FilterControl.GetUniqueIDRelativeTo(label);
        }

        protected override void OnPreRenderComplete(EventArgs e)
        {
            RouteValueDictionary routeValues = new RouteValueDictionary(GridView1.GetDefaultValues());

            var buttonName = String.Format("Create {0}", table.DisplayName);
            var insertUrl = table.GetActionPath(PageAction.Insert, routeValues);
            //InsertHyperLink.NavigateUrl = insertUrl;
            InsertHyperLinkText.PostBackUrl = insertUrl;
            //InsertHyperLink.ToolTip = buttonName;
            InsertHyperLinkText.Text = buttonName;
            InsertHyperLinkText.ToolTip = buttonName;

            if (!InsertHyperLinkText.Visible && !ExportSpan.Visible && !ShowAllColumnsCheckbox.Visible)
                GridViewHeader.Visible = false;

            base.OnPreRenderComplete(e);
        }

        protected void DynamicFilter_FilterChanged(object sender, EventArgs e)
        {
            GridView1.PageIndex = 0;
        }

        protected void ClearFiltersButton_Click(object sender, EventArgs e)
        {
            Page.ClearTableFilters(table);
            Response.Redirect(Page.Request.Url.PathAndQuery);
        }

        protected void btnMultiColumnSearch_Click(object sender, EventArgs e)
        {
            var button = (Button)sender;
            if (button.ID == btnMultiColumnSearchClear.ID)
                txbMultiColumnSearch.Text = String.Empty;

            Page.AddCustomFilterValueToSession(table, table.Name + Global.MULTI_COLUMN_SEARCH, txbMultiColumnSearch.Text);
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            if (GridView1 != null)
                GridView1.Export(showAllColumns: ShowAllColumnsCheckbox.Checked);
        }

        protected void GridView1_PageIndexChanged(object sender, EventArgs e)
        {
            Page.AddCustomFilterValueToSession(table, table.Name + Global.CURRENT_PAGER_PAGE, GridView1.PageIndex);
        }

        /// <summary>
        /// Fixes the sort by column issue with EF
        /// see http://forums.asp.net/p/1528965/3811692.aspx#3811692
        /// </summary>
        protected void GridDataSource_Selecting(object sender, EntityDataSourceSelectingEventArgs e)
        {
            string s = e.SelectArguments.SortExpression;
            if (s.StartsWith("it."))
                e.SelectArguments.SortExpression = s.Substring(3);
        }
    }
}
